<template>
  <inline-Modal
    :visible="visible"
    title="查看"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <div class="allocation-detail-container">
      <div class="header-search">
        <a-select
          showSearch
          :filter-option="filterOption"
          allowClear
          v-model="orgCode"
          placeholder="请选择标段"
          style="width: 200px"
          @change="getTreeData()"
        >
          <a-select-option
            :value="item.orgCode"
            v-for="item in blockNameSource"
            :key="item.id"
          >
            {{ item.orgName }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="getTreeData()"> 查询 </a-button>
      </div>
      <div class="body-container">
        <div class="tree-container">
          <div class="header" header="评价指标"></div>
          <div class="tip">
            项目考核总评分/总分： <span>{{ resultData.finalScore || "-" }}</span
            >/{{ resultData.totalScore || "-" }} 分
          </div>
          <div class="search">
            <a-input-search
              @change="onChange($event)"
              style="width: 100%"
              placeholder="请输入关键词"
            />
          </div>
          <div class="tree-data">
            <a-empty v-if="treeData.length == 0" />
            <a-tree
              v-if="treeData.length > 0 && showTree"
              show-icon
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childs',
                title: 'evaluationName',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <template
                slot="title"
                slot-scope="{ evaluationName, finalScore, totalScore }"
              >
                <div class="custom-tree-item flex" :title="evaluationName">
                  <div class="label">{{ evaluationName }}</div>
                  <div class="value">
                    <span>{{ finalScore || 0 }}</span
                    >/{{ totalScore || 0 }}分
                  </div>
                </div>
              </template>
              <!-- 文件夹图标 -->
              <template slot="custom" slot-scope="{ expanded, childs }">
                <a-icon
                  :type="
                    childs && childs.length > 0
                      ? expanded
                        ? 'folder-open'
                        : 'folder'
                      : 'file'
                  "
                  :class="
                    childs && childs.length > 0 ? 'folder-icon' : 'file-icon'
                  "
                />
              </template>
            </a-tree>
          </div>
        </div>
        <div class="right-container">
          <div class="header" header="任务分配"></div>
          <div class="list">
            <vxe-table
              ref="xTable"
              height="99%"
              align="center"
              size="small"
              border="inner"
              show-overflow
              show-header-overflow
              :data="tableData"
              :column-config="{ resizable: true }"
              :loading="loading"
            >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column field="assessmentContent" title="五级指标">
              </vxe-column>
              <vxe-column field="proStatusDesc" title="项目状态" width="140">
              </vxe-column>
              <vxe-column field="orgName" title="责任主体"> </vxe-column>
              <vxe-column field="determine" title="判定标准"> </vxe-column>
              <vxe-column title="专家评分/自评分/总分（分）">
                <template #default="{ row }">
                  {{ row.finalScore || "-" }}/{{ row.ownScore || "-" }}/{{
                    row.singleScore || "-"
                  }}
                </template>
              </vxe-column>
              <vxe-column title="状态" width="80">
                <template #default="{ row }">
                  <div :class="[checkStatusClass(row), 'status-text']">
                    {{ checkStatusName(row) }}
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="deadline" title="资料上传截止时间" width="140">
              </vxe-column>
              <vxe-column
                field="operate"
                width="80"
                title="操作"
                fixed="right"
                align="left"
              >
                <template #default="{ row }">
                  <div class="text-button-group">
                    <a-button
                      type="link"
                      @click="gotoDetail(row)"
                      v-if="row.view"
                    >
                      查看
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <!-- <div class="pager-container">
            <vxe-pager
              size="small"
              background
              :current-page.sync="pager.page"
              :page-size.sync="pager.pageSize"
              :total="pager.total"
              :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
              :page-sizes="[20, 50, 100, 500]"
              @page-change="paginationChange"
            >
              <template #left>
                <div class="vxe-pager-left-tip-container">
                  共<span>{{ pager.total }}</span
                  >条
                </div>
              </template>
            </vxe-pager>
          </div> -->
        </div>
      </div>
    </div>

    <detailModal
      :visible.sync="detailModalVisible"
      :soucre="dataSoucre"
      @cancel="detailCancel()"
    ></detailModal>
  </inline-Modal>
</template>

<script>
import { addAttributeByKey } from "@/utils/index.js";
import { flatTreeData } from "@/utils/util";
import { axios } from "@/utils/request";
import detailModal from "./detailModal";
export default {
  components: {
    detailModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    soucre: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      showTree: true,
      resultData: {},
      //标段
      orgCode: undefined,
      blockLoading: false,
      blockNameSource: [],
      //分页
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 999,
        total: 0,
      },
      //树
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      treeId: "",
      dataList: [],
      searchValue: "",
      detailModalVisible: false,
      dataSoucre: {},
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    //查看
    gotoDetail(row) {
      let { orgCode = "" } = this;
      let { uuid, tenantCode } = this.soucre;
      this.detailModalVisible = true;
      this.dataSoucre = {
        orgCode,
        taskId: uuid,
        tenantCode,
        id: row.uuid,
      };
    },
    detailCancel() {
      this.detailModalVisible = false;
      this.getData();
    },

    getData() {
      Promise.all([
        this.getDepartmentList(),
        this.getTotalScore(),
        this.getTreeData(),
      ])
        .then()
        .finally((_) => {});
    },
    //查询总分
    getTotalScore() {
      return new Promise((resolve, reject) => {
        let { uuid } = this.soucre;
        let { orgCode = "" } = this;
        axios
          .get(
            `/probusiness/qeTaskAllocation/getTotalData?id=${uuid}&orgCode=${orgCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.resultData = res?.data ?? {};
            resolve();
          })
          .catch((_) => {
            this.resultData = {};
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询标段
    getDepartmentList() {
      this.blockLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode = "" } = this.soucre;
        axios
          .get(
            `/mdata/sysOrgExtend/getOrgExtendListByQX?tenantCode=${tenantCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.blockNameSource = res?.data || [];
            resolve();
          })
          .catch((_) => {
            this.blockNameSource = [];
            reject();
          })
          .finally((_) => {
            this.blockLoading = false;
          });
      });
    },

    //查询评价指标
    getTreeData() {
      this.loading = true;
      let { uuid } = this.soucre;
      let { orgCode = "" } = this;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/qeTaskAllocation/getPJZBViewList?id=${uuid}&orgCode=${orgCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let source = res?.data || [];
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childs"
            );
            this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //查询表格
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { uuid } = this.soucre;
      let { orgCode, treeId } = this;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/qeTaskAllocation/getPJZBContentViewList?pageNo=${page}&pageSize=${pageSize}`,
            {
              id: uuid,
              orgCode,
              evaluationId: treeId,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.tableData = res?.data?.rows || [];
            this.pager.total = res?.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childs");
      let item = flatData.find((v) => !v.childs || v.childs.length == 0);
      this.expandedKeys = [item.uuid];
      this.selectedKeys = [item.uuid];
      this.treeId = item.uuid;
      this.pager.page = 1;
      this.getTableData();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onSelect(expandedKeys, ev) {
      let { node } = ev;
      let { uuid = "" } = node?.dataRef || {};
      this.selectedKeys = [uuid];
      this.treeId = uuid;
      this.pager.page = 1;
      this.getTableData();
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    onChange(e) {
      const value = e.target.value;
      this.showTree = true;
      let { treeData } = this;
      if (value.trim() == "") {
        this.getTreeData();
        return;
      }
      let flatData = flatTreeData(treeData, "childs");
      let result = flatData.filter((v) => v.evaluationName.includes(value));
      //推行标准化
      this.expandedKeys = result.map((v) => v.uuid);
      this.selectedKeys = result.map((v) => v.uuid);
      this.treeId = this.selectedKeys[0] || "";
      this.pager.page = 1;
      if (result.length > 0) {
        this.showTree = false;
        setTimeout((_) => {
          this.showTree = true;
        }, 10);
      }

      this.getTableData();
    },

    //校验状态名称
    checkStatusName(row) {
      let { status } = row;
      switch (status) {
        case 0:
          return "待上传";

        case 1:
          return "已上传";

        case 2:
          return "待审批";

        case 3:
          return "已驳回";

        case 4:
          return "已完成";

        default:
          return "--";
      }
    },
    //校验状态className
    checkStatusClass(row) {
      let { status } = row;
      switch (status) {
        case 0:
          return "cancel";

        case 1:
          return "warn";

        case 2:
          return "lock";

        case 3:
          return "error";

        case 4:
          return "normal";

        default:
          return "cancel";
      }
    },

    handelCancel() {
      this.$emit("cancel");
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
.allocation-detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header-search {
    display: flex;
    border-bottom: 2px solid @border-color;
    padding: 0 0 10px 0;
    /deep/.ant-select {
      margin-right: 16px;
    }
  }
  .header {
    padding: 20px 0;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 0;
    &::before {
      content: attr(header);
      height: 18px;
      border-left: 3px solid @primary-color;
      padding-left: 10px;
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #525a5d;
      line-height: 18px;
    }
  }
  .body-container {
    flex: 1;
    display: flex;
    overflow: hidden;
    .tree-container {
      display: flex;
      flex-direction: column;
      border-right: 2px solid @border-color;
      width: 344px;
      flex-shrink: 0;
      overflow: hidden;
      .tip {
        padding: 0 0 10px 0;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #0098ff;
        > span {
          font-size: 16px;
          font-weight: 700;
        }
      }
      .search {
        padding: 0 10px 10px 0;
      }
      .tree-data {
        flex: 1;
        box-sizing: border-box;
        padding: 0 10px 0px 10px;
        overflow: auto;
        position: relative;
        /deep/.ant-tree {
          .ant-tree-node-content-wrapper {
            width: calc(100% - 34px);
            &.ant-tree-node-selected {
              background: #f5f7fc !important;
              color: @primary-color;
            }
            .folder-icon {
              color: #f5a623;
            }
            .file-icon {
              color: #54baff;
            }
            .ant-tree-title {
              width: calc(100% - 24px);
              display: inline-block;
              .custom-tree-item {
                width: 100%;
                height: 100%;
                .label {
                  flex: 1;
                  overflow: hidden;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  margin-right: 10px;
                }
                .value {
                  color: #525a5d;
                  span {
                    color: @primary-color;
                  }
                }
              }
            }
          }
        }
        .ant-empty {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
    .right-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding-left: 14px;
      .list {
        height: 100%;
        flex: 1;
        .status-text {
          border-radius: 4px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0 auto;
          font-size: 12px;
          width: 60px;
          &.normal {
            background: #4bc964;
          }
          &.warn {
            background: #ff993f;
          }

          &.error {
            background: #ff3f4a;
          }

          &.lock {
            background: #0098ff;
          }
          &.cancel {
            background: #f1f2f7;
            color: #aab0bc;
          }
        }
      }
      .pager-container {
        flex-shrink: 0;
      }
    }
  }
}
</style>
